//hhhhhhh
Page({
  data: {
    showDialog: false,
    form: {
      name: '',
      phone: '',
      detail: ''
    },
    addressList: [],
    selectedIdx: null
  },
  onLoad() {
    this.loadAddressList();
  },
  onShow() {
    this.loadAddressList();
  },
  loadAddressList() {
    const list = wx.getStorageSync('addressList') || [];
    this.setData({ addressList: list });
  },
  showAddDialog() {
    wx.navigateTo({ url: '/pages/address/add' });
  },
  hideAddDialog() {
    this.setData({ showDialog: false });
  },
  onInputName(e) {
    this.setData({ 'form.name': e.detail.value });
  },
  onInputPhone(e) {
    this.setData({ 'form.phone': e.detail.value });
  },
  onInputDetail(e) {
    this.setData({ 'form.detail': e.detail.value });
  },
  saveAddress() {
    const { name, phone, detail } = this.data.form;
    if (!name || !phone || !detail) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }
    let list = wx.getStorageSync('addressList') || [];
    list.unshift({ name, phone, detail });
    wx.setStorageSync('addressList', list);
    wx.showToast({ title: '保存成功', icon: 'success' });
    this.setData({ showDialog: false, form: { name: '', phone: '', detail: '' } });
    this.loadAddressList();
  },
  onEditAddress(e) {
    const idx = e.currentTarget.dataset.idx;
    wx.navigateTo({ url: `/pages/address/add?idx=${idx}` });
  },
  onSelectAddress(e) {
    const idx = e.currentTarget.dataset.idx;
    if (this.data.selectedIdx === idx) {
      this.setData({ selectedIdx: null });
    } else {
      this.setData({ selectedIdx: idx });
    }
  }
});
